package com.graceplayer.service;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.location.GpsStatus;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.provider.MediaStore;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.graceplayer.activity.MainActivity;
import com.graceplayer.activity.R;
import com.graceplayer.data.Music;
import com.graceplayer.data.MusicList;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

public class MusicService extends Service {
    public static final int COMMAND_UNKNOWN=-1;
    public static final int COMMAND_PLAY=0;
    public static final int COMMAND_PAUSE=1;
    public static final int COMMAND_STOP=2;
    public static final int COMMAND_RESUME=3;
    public static final int COMMAND_PREVIOUS=4;
    public static final int COMMAND_NEXT=5;
    public static final int COMMAND_CHECK_IS_PLAYING=6;
    public static final int COMMAND_SEEK_TO=7;
    public static final int COMMAND_RANDOM=8;

    public static final int STATUS_PLAYING=0;
    public static final int STATUS_PAUSED=1;
    public static final int STATUS_STOPPED=2;
    public static final int STATUS_COMPLETED=3;

    public static final String BROADCAST_MUSICSERVICE_CONTROL="MusicServie.ACTION_CONTROL";
    public static final String BROADCAST_MUSICSERVICE_UPDATE_STATUS="MusicService.ACTION_UPDATE";
    public static final String BROADCAST_MUSICSERVICE_UPDATE_PROGRESS="MusicService.PROGRESS_UPDATE";
    public static final String BROADCAST_MUSICSERVICE_MUSIC_STATUS="MusicService.MUSIC_UPDATE";

    private int status=-1;

    private CommandReceiver receiver;

    private MediaPlayer player = new MediaPlayer();
    private int number = 0;
    private int maxTime;
    private int i=0;
    //校正暂停时间（ms to s）
    private int pauseTime=0;
    //private boolean first=false;

    private boolean phone=false;

    public IBinder onBind(Intent intent){
        return null;
    }
    public void onCreate(){
        super.onCreate();
        TelephonyManager telephonyManager=(TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        telephonyManager.listen(new MyPhoneListener(), PhoneStateListener.LISTEN_CALL_STATE);
        bindCommandReceiver();
    }
    public int onStartCommand(Intent intent,int flags,int startId){
        return super.onStartCommand(intent,flags,startId);
    }
    public void onDestroy(){
        super.onDestroy();
    }
    public boolean onUnbind(Intent intent){
        return super.onUnbind(intent);
    }
    private  final class MyPhoneListener extends PhoneStateListener{
        public void onCallStateChanged(int state,String incomingNumber){
            switch (state){
                case TelephonyManager.CALL_STATE_RINGING:
                    if (state==MusicService.STATUS_PLAYING){
                        pause();
                        phone=true;
                    }
                    break;
                case TelephonyManager.CALL_STATE_IDLE:
                    if(phone==true){
                        resume();
                        phone=false;
                    }
                    break;
            }
        }
    }
    class CommandReceiver extends BroadcastReceiver{
        public void onReceive(Context context,Intent intent){
            int command=intent.getIntExtra("command",COMMAND_UNKNOWN);
            Log.d("收到的command", String.valueOf(command));
            switch (command){
                case COMMAND_PLAY:
                    number=intent.getIntExtra("number",0);
                    Log.d("歌曲序号", String.valueOf(number));
                    play(number);
                    break;
                case COMMAND_PREVIOUS:
                    moveNumberToPrevious();
                    break;
                case COMMAND_NEXT:
                    moveNumberToNext();
                    break;
                case COMMAND_PAUSE:
                    pause();
                    break;
                case COMMAND_STOP:
                    stop();
                    break;
                case COMMAND_RESUME:
                    resume();
                    break;
                case COMMAND_CHECK_IS_PLAYING:
                    if(player!=null&&player.isPlaying()){
                        sendBroadcastOnStatusChanged(MusicService.STATUS_PLAYING);
                    }
                    break;
                case COMMAND_SEEK_TO:
                    i=intent.getIntExtra("seek",0);
                    Log.d("进度条被改变", String.valueOf(i*1000));
                    pauseTime=i*1000;
                    player.seekTo( (int)i*1000);
                    sendBroadcastOnSeekBarChanged();
                    resume();
                    //play(number);
                    break;
                case COMMAND_RANDOM:
                    Random rand=new Random();
                    int n=rand.nextInt(MusicList.getMusicList().size()-1);
                    do{
                        //不要-1，不然会轮不到最后一首歌
                        n=rand.nextInt(MusicList.getMusicList().size());
                    }while (n==number);
                    number=n;
                    play(number);
                    break;
                case COMMAND_UNKNOWN:
                default:break;
            }
        }
    }
    private void bindCommandReceiver(){
        receiver = new CommandReceiver();
        IntentFilter filter=new IntentFilter(BROADCAST_MUSICSERVICE_CONTROL);
        registerReceiver(receiver,filter);
    }
    private void sendBroadcastOnStatusChanged(int status){
        Intent intent = new Intent(BROADCAST_MUSICSERVICE_UPDATE_STATUS);
        intent.putExtra("status",status);
        if(status!=STATUS_STOPPED){
            intent.putExtra("playingNumber",number);
            intent.putExtra("musicName",MusicList.getMusicList().get(number).getmusicName());
            intent.putExtra("musicArtist",MusicList.getMusicList().get(number).getmusicArtist());
        }
        sendBroadcast(intent);
    }
    private void sendBroadcastOnMusicInfoChanged(){
        Intent intent = new Intent(BROADCAST_MUSICSERVICE_MUSIC_STATUS);
        maxTime=player.getDuration()/1000;
        intent.putExtra("duration",maxTime);
        sendBroadcast(intent);
    }
    private void load(int number) {
        try {
            player.reset();
            player.setDataSource(MusicList.getMusicList().get(number).getmusicPath());
            player.prepare();
            sendBroadcastOnMusicInfoChanged();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        player.setOnCompletionListener(completionListener);
    }
    MediaPlayer.OnCompletionListener completionListener=new MediaPlayer.OnCompletionListener() {
        @Override
            public void onCompletion(MediaPlayer player){
                if(player.isLooping()){
                    replay();
                }else {
                    sendBroadcastOnStatusChanged(MusicService.STATUS_COMPLETED);
                }
            }
    };
    private void play(int number) {
        if (player != null && player.isPlaying()) {
            player.stop();
        }
        load(number);
        /*
        first=false;
        int x=player.getDuration()/1000;
        progressBar.setMax(x);
        musicTimeText.setText((x/60<10?"0":"")+String.valueOf(x/60)+":"+(x%60<10?"0":"")+String.valueOf(x%60));
        updateBarHandler.removeCallbacks(updateThread);
        player.seekTo(i*1000);
        */
        updateBarHandler.removeCallbacks(updateThread);
        i=0;
        pauseTime=0;
        //first=false;
        updateBarHandler.postDelayed(updateThread,1000-pauseTime%1000);
        player.start();
        status=MusicService.STATUS_PLAYING;
        sendBroadcastOnStatusChanged(MusicService.STATUS_PLAYING);
    }
    //切换下一首或上一首后，计时器双倍计数，点击暂停再开始后恢复正常bug
    private void pause() {
        if (player.isPlaying()) {
            updateBarHandler.removeCallbacks(updateThread);
            pauseTime=player.getCurrentPosition();
            player.pause();
            status=MusicService.STATUS_PAUSED;
            sendBroadcastOnStatusChanged(MusicService.STATUS_PAUSED);
        }
    }
    private void stop() {
        updateBarHandler.removeCallbacks(updateThread);
        //playedTime.setText("00:00");
        //progressBar.setProgress(0);
        if(status!=MusicService.STATUS_STOPPED) {
            i=0;
            pauseTime=0;
            player.stop();
            status=MusicService.STATUS_STOPPED;
            sendBroadcastOnStatusChanged(MusicService.STATUS_STOPPED);
            sendBroadcastOnSeekBarChanged();
        }
    }
    private void resume() {
        updateBarHandler.removeCallbacks(updateThread);
        //疯狂按暂停和开始会导致进度不一致
        updateBarHandler.postDelayed(updateThread,1000-pauseTime%1000);
        player.start();
        player.seekTo(pauseTime);
        pauseTime=0;
        status=MusicService.STATUS_PLAYING;
        sendBroadcastOnStatusChanged(MusicService.STATUS_PLAYING);
    }
    private void replay() {
        updateBarHandler.removeCallbacks(updateThread);
        i=0;
        pauseTime=0;
        player.start();
        status=MusicService.STATUS_PLAYING;
        sendBroadcastOnStatusChanged(MusicService.STATUS_PLAYING);
    }

    private void moveNumberToNext() {
        if ((number ) == MusicList.getMusicList().size()-1) {
            Toast.makeText(MusicService.this,"当前为最后一首歌曲，将跳转至第一首歌曲",Toast.LENGTH_SHORT).show();
            number=0;
        } else {
            ++number;
        }
        updateBarHandler.removeCallbacks(updateThread);
        i=0;
        play(number);
    }
    private void moveNumberToPrevious() {
        if (number == 0) {
            Toast.makeText(MusicService.this,"当前为第一首歌曲，将跳转至最后一首歌曲",Toast.LENGTH_SHORT).show();
            number = MusicList.getMusicList().size()-1;
        } else {
            --number;
        }
        updateBarHandler.removeCallbacks(updateThread);
        i=0;
        play(number);
    }

    private void sendBroadcastOnSeekBarChanged(){
        Intent intent = new Intent(BROADCAST_MUSICSERVICE_UPDATE_PROGRESS);
        intent.putExtra("progress",i);
        intent.putExtra("playedTime",(i/60<10?"0":"")+String.valueOf(i/60)+":"+(i%60<10?"0":"")+String.valueOf(i%60));
        sendBroadcast(intent);
    }

    Handler updateBarHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    };
    Runnable updateThread=new Runnable() {
        @Override
        public void run() {
            i=i==0?0:i;
            i++;
            System.out.println("Begin Thread");
            Log.d("时间tag", String.valueOf(i));
            sendBroadcastOnSeekBarChanged();
            //新建updateBarHandler的Message对象
            if(i==maxTime){
                i=0;
                sendBroadcastOnSeekBarChanged();
                updateBarHandler.removeCallbacks(updateThread);
            }else{updateBarHandler.postDelayed(updateThread,1000);}
            //校正计时
        }
    };
}
